package com.interesting.examsystem.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author ：ZXY
 * @date ：Created in 2021/2/22 17:05
 * @description：Spirng上下文工具
 * @modified By：`
 * @version: 1.0
 */
@Component
public class SpringContextUtil
        implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        if (applicationContext != null) {
            return applicationContext.getBean(name);
        }
        return null;
    }

    public static Object getEnvProper(String name) throws BeansException {
        if (applicationContext != null) {
            return applicationContext.getEnvironment().getProperty(name);
        }
        return null;
    }

    public static void publish(Object object) throws BeansException {
        if (applicationContext != null)
            applicationContext.publishEvent(object);
    }
}
